# scheduler.py (调度管理)
from apscheduler.schedulers.blocking import BlockingScheduler
import time
from prometheus_client import start_http_server
import logging
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
from datetime  import datetime


class JobScheduler:
    def __init__(self, config):
        # 初始化配置
        self.config = config
        self.logger = logging.getLogger('capture_task')
        # 医疗系统专用配置
        medical_config = {
            'apscheduler.executors': {
                'default': {'type': 'threadpool', 'max_workers': 1}  # 严格单线程
            },
            'apscheduler.job_defaults': {
                'coalesce': True,  # 合并积压任务
                'max_instances': 1,  # 防止任务重叠
                'misfire_grace_time': 300  # 医疗任务宽限期
            }
        }

        self.scheduler = BlockingScheduler(
            executors=medical_config['apscheduler.executors'],
            job_defaults=medical_config['apscheduler.job_defaults']
        )

        self._init_metrics()

        # 需要添加以下方法

    def _init_metrics(self):
        """初始化监控指标（示例逻辑）"""
        self.metrics = {
            "jobs": [],
            "status": "idle",
            "success": 0,
            "failed": 0,
            "last_run": None
        }

    def add_job(self, func, trigger_type, task_id, **trigger_args):
        print(f"Adding job with trigger: {trigger_type}, params: {trigger_args}")
        if trigger_type == "cron":
            trigger = CronTrigger(**trigger_args)
        elif trigger_type == "interval":
            trigger = IntervalTrigger(**trigger_args)

        self.scheduler.add_job(
                func,
                trigger=trigger,
                max_instances=1,
                next_run_time=datetime.now(),
                task_id=task_id
            )
        self.logger.info(f"定时任务已注册: {task_id}")

    def job_wrapper(self, job_func, task_name):
        def wrapped():
            try:
                start = time.time()
                job_func()
                self.metrics['success_count'][task_name] += 1
            except Exception as e:
                self.metrics['error_count'][task_name] += 1
                self.logger.error(f"Task {task_name} failed: {str(e)}")
            finally:
                self.metrics['last_execution'][task_name] = {
                    'time': time.time(),
                    'duration': time.time() - start
                }

        return wrapped

    def start(self):
        start_http_server(self.config['app']['metrics_port'])
        self.scheduler.start()